package com.springcloud.study.consumer.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Description: TODO
 * @Author dongguo
 * @Date 2020/4/7 16:22
 * @Version V1.0
 **/

@RestController
public class CallHelloController {

    @Autowired
    private LoadBalancerClient loadBalancer;
    @Autowired
    private DiscoveryClient discoveryClient;


    @GetMapping("/call")
    public String call() {
        ServiceInstance serviceInstance = loadBalancer.choose("service-producer");
        System.out.println("服务地址：" + serviceInstance.getUri());
        System.out.println("服务名称：" + serviceInstance.getServiceId());

        String callServiceResult = new RestTemplate().getForObject(serviceInstance.getUri().toString() + "/hello", String.class);
        System.out.println(callServiceResult);

        System.out.println("-----------------------------------------------------------");
        List<ServiceInstance> list = discoveryClient.getInstances("service-producer");
        if (list != null && list.size() > 0 ) {
            for (ServiceInstance instance : list){
                System.out.println(JSONObject.toJSONString(instance));
                System.out.println("服务地址：" + instance.getUri());
                System.out.println("服务名称：" + instance.getServiceId());
            }
        }
        return callServiceResult;
    }


}
